/**
 * 明细账查询 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0002.AccQuery.DetailMainForm", {
  extend: "PSI.AFX.Form.MainForm",

  config: {
    permission: null
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      items: [{
        tbar: me.getToolbarCmp(),
        id: me.buildId(me, "panelQueryCmp"),
        region: "north",
        height: 100,
        header: false,
        collapsible: true,
        collapseMode: "mini",
        border: 0,
        layout: {
          type: "table",
          columns: 5
        },
        bodyCls: "PSI-Query-Panel",
        items: me.getQueryCmp()
      }, {
        region: "center",
        layout: "border",
        border: 0,
        ...PSI.Const.BODY_PADDING,
        items: [{
          region: "center",
          layout: "border",
          split: true,
          border: 0,
          items: [{
            region: "north",
            id: me.buildId(me, "panelInfo"),
            height: 35,
            border: 0,
            html: "<h3 style='margin:0px;border-left:5px #9254de solid;padding-left:2px'>请选择账簿</h3>",
          },
          {
            region: "center",
            border: 1,
            layout: "fit",
            items: me.getMainGrid(),
          }
          ],
        }]
      }]
    });

    me.callParent(arguments);

    me.editQueryOrg = PCL.getCmp(me.buildId(me, "editQueryOrg"));
    me.editQueryPeriodYear = PCL.getCmp(me.buildId(me, "editQueryPeriodYear"));
    me.editQueryPeriodMonth = PCL.getCmp(me.buildId(me, "editQueryPeriodMonth"));
    me.panelQueryCmp = PCL.getCmp(me.buildId(me, "panelQueryCmp"));

    me.panelInfo = PCL.getCmp(me.buildId(me, "panelInfo"));

    me._keyMapMain = PCL.create("PCL.util.KeyMap", PCL.getBody(), [{
      key: "H",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        const panel = me.panelQueryCmp;
        if (panel.getCollapsed()) {
          panel.expand();
        } else {
          panel.collapse();
        };
      },
      scope: me
    },
    ]);

    me.queryCompanyList();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;

    let result = [];
    let list = [];

    result.push({
      text: "选择账簿",
      iconCls: "PSI-tb-new",
      ...PSI.Const.BTN_STYLE,
      handler: me._onSelectAcc,
      scope: me
    }, "-", {
      text: "新窗口打开本模块",
      ...PSI.Const.BTN_STYLE,
      tooltip: me.buildTooltip("当需要多账簿对照的时候，可以使用本功能"),
      handler() {
        me.focus();
        window.open(me.URL("Home/MainMenu/navigateTo/fid/2111"));
      }
    });

    // 实施配置工具
    list = [];
    if (me.getPermission().saveLayout == "1") {
      result.push("-");
      list.push({
        text: "保存列视图布局",
        scope: me,
        handler: me._onSaveViewLayout
      });

      result.push({
        text: "实施配置工具",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    // 指南
    // 关闭
    if (result.length > 0) {
      result.push("-");
    }
    result.push({
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("/Home/Help/index?t=accQuery"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    });

    result = result.concat(me.getShortcutCmp());

    return result;
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["->",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
   * 查询条件
   * 
   * @private
   */
  getQueryCmp() {
    const me = this;

    const modelName = me.buildModelName(me, "QueryOrg");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    return [{
      xtype: "container",
      height: 26,
      html: `<h2 style='margin-left:20px;margin-top:18px;color:#595959;display:inline-block'>明细分类账查询</h2>
                &nbsp;&nbsp;<span style='color:#8c8c8c'>明细分类账账簿查询</span>
                <div style='float:right;display:inline-block;margin:10px 0px 0px 20px;border-left:1px solid #e5e6e8;height:40px'>&nbsp;</div>
                `
    }, {
      id: me.buildId(me, "editQueryOrg"),
      labelWidth: 70,
      width: 490,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "组织机构",
      margin: "10, 0, 0, 0",
      xtype: "combobox",
      queryMode: "local",
      editable: false,
      valueField: "id",
      displayField: "name",
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        },
        select: {
          fn: me._onComboOrgSelect,
          scope: me
        },
      },
      colspan: 4,
    }, { xtype: "container" }, {
      id: me.buildId(me, "editQueryPeriod"),
      labelWidth: 70,
      width: 320,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "会计期间",
      margin: "5, 0, 0, 0",
      xtype: "fieldcontainer",
      layout: "hbox",
      items: [
        {
          xtype: "numberfield",
          hideTrigger: true,
          allowDecimals: false,
          width: 40,
          value: (new Date()).getFullYear(),
          id: me.buildId(me, "editQueryPeriodYear"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, { xtype: "displayfield", value: "年", width: 15, }, {
          xtype: "combobox",
          width: 70,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[1, "一月"], [2, "二月"],
            [3, "三月"], [4, "四月"],
            [5, "五月"], [6, "六月"],
            [7, "七月"], [8, "八月"],
            [9, "九月"], [10, "十月"],
            [11, "十一月"], [12, "十二月"]]
          }),
          valueField: "id",
          displayFIeld: "text",
          queryMode: "local",
          editable: false,
          value: (new Date()).getMonth() + 1,
          id: me.buildId(me, "editQueryPeriodMonth"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          xtype: "button",
          text: "上一月",
          margin: "0 0 0 5",
          handler: me._onPriorMonth,
          scope: me,
        }, {
          xtype: "button",
          text: "下一月",
          handler: me._onNextMonth,
          scope: me,
        }
      ],
    }, {
      xtype: "container",
      colspan: 2,
      items: [{
        xtype: "button",
        text: "查询",
        cls: "PSI-Query-btn1",
        width: 100,
        height: 26,
        margin: "5 0 0 10",
        handler: me._onQuery,
        scope: me
      }, {
        xtype: "button",
        text: "隐藏工具栏 <span class='PSI-shortcut-DS'>Alt + H</span>",
        cls: "PSI-Query-btn3",
        width: 140,
        height: 26,
        iconCls: "PSI-button-hide",
        margin: "5 0 0 20",
        handler() {
          me.panelQueryCmp.collapse();
        },
        scope: me
      }]
    },];
  },

  /**
   * @private
   */
  queryCompanyList() {
    const me = this;
    const store = me.editQueryOrg.getStore();
    const r = {
      url: me.URL("SLN0002/AccQuery/companyList"),
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (data.length > 0) {
            const companyId = data[0]["id"];
            me.editQueryOrg.setValue(companyId);

            // 把编辑器设置为只读，因为只能在选择账簿界面中改变当前组织机构
            me.editQueryOrg.setReadOnly(true);
            me._currentCompanyId = companyId;
          }
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  _onComboOrgSelect() {
    const me = this;
  },

  /**
   * @private
   */
  _onQuery() {
    const me = this;

    if (!me._currentAccNumber) {
      me._onSelectAcc.apply(me);
      return;
    }

    me.getMainGrid().getStore().reload();
  },

  /**
   * @private
   */
  _onSelectAcc() {
    const me = this;

    const form = PCL.create("PSI.SLN0002.AccQuery.SelectAccForm", {
      renderTo: PSI.Const.RENDER_TO(),
      parentForm: me,
      currentCompanyId: me._currentCompanyId,
      currentYear: me.editQueryPeriodYear.getValue(),
      currentMonth: me.editQueryPeriodMonth.getValue(),
      accNumber: me._currentAccNumber, // 账簿码
    });
    form.show();
  },

  /**
   * @private
   * 
   * PSI.SLN0002.AccQuery.SelectAccForm回调本方法
   */
  _onSelectAccCallback(currentCompanyId, currentYear, currentMonth, accNumber, subAccLevel, subAccList, accName) {
    const me = this;

    me._currentCompanyId = currentCompanyId;
    me.editQueryOrg.setValue(currentCompanyId);
    me.editQueryPeriodYear.setValue(currentYear);
    me.editQueryPeriodMonth.setValue(currentMonth);
    me._currentAccNumber = accNumber;
    me._currentSubAccLevel = subAccLevel;
    me._currentSubAccList = subAccList; // 当前的明细账的子账簿数组，通常是码表的code

    me.panelInfo.getEl().setHTML(`<h3 style='margin:2px;border-left:5px #9254de solid;padding-left:2px'>${accName}</h3>`);

    me.queryFmt();
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;

    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "AccDetailData");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "subject", "debit", "credit", "balance", "balanceDir"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 100,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0002/AccQuery/queryAccDetailData"),
        reader: {
          root: 'dataList',
          totalProperty: 'totalCount'
        }
      }
    });
    store.on("beforeload", () => {
      store.proxy.extraParams = me.getMainParams();
    });

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      border: 0,
      tbar: [{
        xtype: "button",
        text: "选择账簿",
        iconCls: "PSI-tb-new",
        width: 100,
        height: 26,
        handler: me._onSelectAcc,
        scope: me
      }, "-", {
        xtype: "displayfield",
        value: "&nbsp;<strong>说明</strong>：双击下面表格中的记录，可以查看对应的记账凭证"
      }, "->", {
        id: me.buildId(me, "ptbMainGrid"),
        border: 0,
        xtype: "pagingtoolbar",
        store,
      }, "-", {
        xtype: "displayfield",
        fieldStyle: "font-size:13px",
        value: "每页显示"
      }, {
        id: me.buildId(me, "comboMainGrid"),
        xtype: "combobox",
        editable: false,
        width: 60,
        store: PCL.create("PCL.data.ArrayStore", {
          fields: ["text"],
          data: [["20"], ["50"], ["100"], ["300"],
          ["1000"]]
        }),
        value: "100",
        listeners: {
          change: {
            fn() {
              store.pageSize = PCL.getCmp(me.buildId(me, "comboMainGrid")).getValue();
              store.currentPage = 1;
              PCL.getCmp(me.buildId(me, "ptbMainGrid")).doRefresh();
            },
            scope: me
          }
        }
      }, {
        xtype: "displayfield",
        fieldStyle: "font-size:13px",
        value: "条账簿记录"
      }],

      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [PCL.create("PCL.grid.RowNumberer", {
          text: "#",
          width: 40
        }), {
          header: "科目",
          dataIndex: "subjectCode"
        }]
      },
      store,
      listeners: {
        itemdblclick: {
          fn: me._onViewVoucher,
          scope: me
        },
      },
    });

    return me._mainGrid;
  },

  /**
   * @private
   */
  getMainParams() {
    const me = this;

    const companyId = me._currentCompanyId;
    const accNumber = me._currentAccNumber;
    const year = me.editQueryPeriodYear.getValue();
    const month = me.editQueryPeriodMonth.getValue();

    const subAccLevel = me._currentSubAccLevel;
    const subAccList = me._currentSubAccList;

    let subAcc01 = "";
    let subAcc02 = "";
    let subAcc03 = "";
    if (subAccLevel == 1) {
      subAcc01 = subAccList[0];
    } else if (subAccLevel == 2) {
      subAcc01 = subAccList[0];
      subAcc02 = subAccList[1];
    } else if (subAccLevel == 3) {
      subAcc01 = subAccList[0];
      subAcc02 = subAccList[1];
      subAcc03 = subAccList[2];
    }

    return {
      companyId,
      accNumber,
      year,
      month,
      subAccLevel,
      subAcc01,
      subAcc02,
      subAcc03,
    };
  },

  /**
   * 查询账簿的账样列
   * @private
   */
  queryFmt() {
    const me = this;

    const companyId = me._currentCompanyId;
    const accNumber = me._currentAccNumber;
    const subAccLevel = me._currentSubAccLevel;

    const grid = me.getMainGrid();
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0002/AccQuery/queryFmtColsForDetailAcc"),
      params: {
        companyId,
        accNumber,
        subAccLevel,
      },
      callback(options, success, response) {
        el?.unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          me._fmtCols = data;

          me.reconfigMainGrid();
          me.queryAccDetailData();
        }
      }
    });
  },

  /**
   * @private
   */
  reconfigMainGrid() {
    const me = this;

    const fields = ["acc_flag"];
    const cols = [PCL.create("PCL.grid.RowNumberer", {
      text: "#",
      width: 40
    })];

    me._fmtCols.forEach((col) => {
      fields.push(col.fieldName);

      const c = {
        dataIndex: col.fieldName,
        header: col.caption,
        width: col.colWidth,
      }

      if (col.fieldName == "acc_db" || col.fieldName == "acc_cr" || col.fieldName == "acc_balance"
        || col.fieldName == "x_db_price" || col.fieldName == "x_cr_price" || col.fieldName == "x_balance_price"
      ) {
        PCL.apply(c, {
          align: "right",
          renderer(value) {
            return me.formatMoney(value);
          }
        });
      }

      if (col.fieldName == "x_db_cnt" || col.fieldName == "x_cr_cnt" || col.fieldName == "x_balance_cnt") {
        PCL.apply(c, {
          align: "right",
        });
      }

      if (col.fieldName == "voucher_summary") {
        PCL.apply(c, {
          renderer(value, metaData, record) {
            const accFlag = parseInt(record.get("acc_flag"))
            if (accFlag == 1000) {
              return `<span style='color:#006d75'>${value}</span>`;
            } else if (accFlag == 2000) {
              return `<span style='color:#006d75'>${value}</span>`;
            } else if (accFlag == 2001) {
              return `<strong style='color:#006d75'>${value}</strong>`;
            } else if (accFlag == 2002) {
              return `<strong style='color:#006d75'>${value}</strong>`;

            } else {
              return value;
            }
          }
        });
      }

      cols.push(c);
    });

    const modelName = me.buildModelName(me, "AccDetailData");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields,
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 100,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0002/AccQuery/queryAccDetailData"),
        reader: {
          root: 'dataList',
          totalProperty: 'totalCount'
        }
      }
    });
    store.on("beforeload", () => {
      store.proxy.extraParams = me.getMainParams();
    });

    me.getMainGrid().reconfigure(store, cols);
  },

  /**
   * @private
   */
  queryAccDetailData() {
    const me = this;

    me.getMainGrid().getStore().reload();
  },

  /**
   * @private
   */
  _onSaveViewLayout() {
    const me = this;

    if (!me._currentAccNumber) {
      me.showInfo("没有选择账簿，无法保存列视图布局");
      return;
    }

    const doSaveViewLayout = () => {
      const columns = me.getMainGrid().columnManager.columns;

      const data = [];
      const widthArray = [];
      for (let i = 0; i < columns.length; i++) {
        const col = columns[i];

        data.push(col.dataIndex);
        widthArray.push(col.width);
      }

      const showOrder = data.join(",");
      const widthList = widthArray.join(",");

      const el = PCL.getBody();
      el.mask("正在操作中...");
      const r = {
        url: me.URL("SLN0002/AccQuery/saveViewLayout"),
        params: {
          companyId: me._currentCompanyId,
          accNumber: me._currentAccNumber,
          idList: showOrder,
          widthList,
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功保存视图布局", true);
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };

    me.confirm("请确认是否保存当前账簿的视图布局?", doSaveViewLayout);
  },

  /**
   * @private
   */
  _onPriorMonth() {
    const me = this;

    let year = me.editQueryPeriodYear.getValue();
    let month = me.editQueryPeriodMonth.getValue();
    month--;
    if (month == 0) {
      year--;
      month = 12;
    }

    me.editQueryPeriodYear.setValue(year);
    me.editQueryPeriodMonth.setValue(month);

    me._onQuery.apply(me);
  },

  /**
   * @private
   */
  _onNextMonth() {
    const me = this;

    let year = me.editQueryPeriodYear.getValue();
    let month = me.editQueryPeriodMonth.getValue();
    month++;
    if (month == 13) {
      year++;
      month = 1;
    }

    me.editQueryPeriodYear.setValue(year);
    me.editQueryPeriodMonth.setValue(month);

    me._onQuery.apply(me);
  },

  /**
   * @private
   */
  _onViewVoucher() {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const record = item[0];

    const year = record.get("voucher_year");
    const month = record.get("voucher_month");
    const word = record.get("voucher_word");
    const num = record.get("voucher_number");
    const jeNumber = record.get("je_number");
    const summary = record.get("voucher_summary");
    if (jeNumber == -1000) {
      me.tip("建账数据，没有对应的记账凭证");
      return;
    }

    // 没有凭证号，提示用户
    if (!num) {
      if (summary) {
        me.tip(`${summary}，没有对应的记账凭证`);
        return;
      }
      return;
    }

    const el = me.getMainGrid().getEl();
    el?.mask(PSI.Const.LOADING);

    me.ajax({
      url: me.URL("SLN0002/AccQuery/queryVoucherId"),
      params: {
        companyId: me._currentCompanyId,
        year,
        month,
        word,
        num,
      },
      callback(options, success, response) {
        el?.unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          if (data.success) {
            const id = data.id;
            me.showVoucherForm(id);
          } else {
            me.tip("不存在记账凭证");
          }
        }
      }
    });
  },

  /**
   * @private
   */
  showVoucherForm(id) {
    const me = this;

    const modelName = me.buildModelName(me, "Voucher");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id"]
    });

    const voucher = PCL.create(modelName, {
      id
    });

    const form = PCL.create("PSI.SLN0002.Voucher.EditForm", {
      parentForm: null,
      entity: voucher,
    });
    form.show();
  },
});
